home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / xulrunner / python / BitTorrent / zurllib.py < prev   
Encoding:
Python Source  |  2007-11-12  |  4.7 KB  |  162 lines

  1. #
  2. # zurllib.py
  3. #
  4. # This is (hopefully) a drop-in for urllib which will request gzip/deflate
  5. # compression and then decompress the output if a compressed response is
  6. # received while maintaining the API.
  7. #
  8. # by Robert Stone 2/22/2003 
  9. #
  10.  
  11. from urllib import *
  12. from urllib2 import *
  13. from gzip import GzipFile
  14. from StringIO import StringIO
  15. from __init__ import version
  16. import pprint
  17. import config
  18. import prefs
  19.  
  20.  
  21. DEBUG=0
  22.  
  23.  
  24. class HTTPContentEncodingHandler(HTTPHandler):
  25.     """Inherit and add gzip/deflate/etc support to HTTP gets."""
  26.     def http_open(self, req):
  27.         # add the Accept-Encoding header to the request
  28.         # support gzip encoding (identity is assumed)
  29.         req.add_header("Accept-Encoding","gzip")
  30.         # Added correct capitalization and Democracy info to string --NN
  31.         req.add_header('User-Agent', 'BitTorrent/%s %s/%s (%s)' % \
  32.                        (version,
  33.                         config.get(prefs.SHORT_APP_NAME),
  34.                         config.get(prefs.APP_VERSION),
  35.                         config.get(prefs.PROJECT_URL)))
  36.  
  37.         if DEBUG: 
  38.             print "Sending:" 
  39.             print req.headers
  40.             print "\n"
  41.         fp = HTTPHandler.http_open(self,req)
  42.         headers = fp.headers
  43.         if DEBUG: 
  44.              pprint.pprint(headers.dict)
  45.         url = fp.url
  46.         resp = addinfourldecompress(fp, headers, url)
  47.         # As of Python 2.4 http_open response also has 'code' and 'msg'
  48.         # members, and HTTPErrorProcessor breaks if they don't exist.
  49.         if 'code' in dir(fp):
  50.             resp.code = fp.code
  51.         if 'msg' in dir(fp):
  52.             resp.msg = fp.msg
  53.         return resp
  54.  
  55. class addinfourldecompress(addinfourl):
  56.     """Do gzip decompression if necessary. Do addinfourl stuff too."""
  57.     def __init__(self, fp, headers, url):
  58.         # we need to do something more sophisticated here to deal with
  59.         # multiple values?  What about other weird crap like q-values?
  60.         # basically this only works for the most simplistic case and will
  61.         # break in some other cases, but for now we only care about making
  62.         # this work with the BT tracker so....
  63.         if headers.has_key('content-encoding') and headers['content-encoding'] == 'gzip':
  64.             if DEBUG:
  65.                 print "Contents of Content-encoding: " + headers['Content-encoding'] + "\n"
  66.             self.gzip = 1
  67.             self.rawfp = fp
  68.             fp = GzipStream(fp)
  69.         else:
  70.             self.gzip = 0
  71.         return addinfourl.__init__(self, fp, headers, url)
  72.  
  73.     def close(self):
  74.         self.fp.close()
  75.         if self.gzip:
  76.             self.rawfp.close()
  77.  
  78.     def iscompressed(self):
  79.         return self.gzip
  80.  
  81. class GzipStream(StringIO):
  82.     """Magically decompress a file object.
  83.  
  84.        This is not the most efficient way to do this but GzipFile() wants
  85.        to seek, etc, which won't work for a stream such as that from a socket.
  86.        So we copy the whole shebang info a StringIO object, decompress that
  87.        then let people access the decompressed output as a StringIO object.
  88.  
  89.        The disadvantage is memory use and the advantage is random access.
  90.  
  91.        Will mess with fixing this later.
  92.     """
  93.  
  94.     def __init__(self,fp):
  95.         self.fp = fp
  96.  
  97.         # this is nasty and needs to be fixed at some point
  98.         # copy everything into a StringIO (compressed)
  99.         compressed = StringIO()
  100.         r = fp.read()
  101.         while r:
  102.             compressed.write(r)
  103.             r = fp.read()
  104.         # now, unzip (gz) the StringIO to a string
  105.         compressed.seek(0,0)
  106.         gz = GzipFile(fileobj = compressed)
  107.         str = ''
  108.         r = gz.read()
  109.         while r:
  110.             str += r
  111.             r = gz.read()
  112.         # close our utility files
  113.         compressed.close()
  114.         gz.close()
  115.         # init our stringio selves with the string 
  116.         StringIO.__init__(self, str)
  117.         del str
  118.  
  119.     def close(self):
  120.         self.fp.close()
  121.         return StringIO.close(self)
  122.  
  123.  
  124. def test():
  125.     """Test this module.
  126.  
  127.        At the moment this is lame.
  128.     """
  129.  
  130.     print "Running unit tests.\n"
  131.  
  132.     def printcomp(fp):
  133.         try:
  134.             if fp.iscompressed():
  135.                 print "GET was compressed.\n"
  136.             else:
  137.                 print "GET was uncompressed.\n"
  138.         except:
  139.             print "no iscompressed function!  this shouldn't happen"
  140.  
  141.     print "Trying to GET a compressed document...\n"
  142.     fp = urlopen('http://a.scarywater.net/hng/index.shtml')
  143.     print fp.read()
  144.     printcomp(fp)
  145.     fp.close()
  146.  
  147.     print "Trying to GET an unknown document...\n"
  148.     fp = urlopen('http://www.otaku.org/')
  149.     print fp.read()
  150.     printcomp(fp)
  151.     fp.close()
  152.  
  153.  
  154. #
  155. # Install the HTTPContentEncodingHandler that we've defined above.
  156. #
  157. install_opener(build_opener(HTTPContentEncodingHandler))
  158.  
  159. if __name__ == '__main__':
  160.     test()
  161.  
  162.